﻿using KYJBLL;
using KYJScadaProModbusRtu;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KYJScadaProModbusRTU
{
    public partial class FrmReport : Form
    {
        public FrmReport()
        {
            InitializeComponent();
            this.cmb_ReportType.SelectedIndexChanged += Cmb_ReportType_SelectedIndexChanged;

            this.cmb_ReportType.Items.Add("小时报表");
            this.cmb_ReportType.Items.Add("日报表");
            this.cmb_ReportType.SelectedIndex = 0;

            if (CommomMethods.plcDevice != null)
            {
                IntialDataGridView();
            }
        }

        //所有归档变了名称和描述的字典集合
        private Dictionary<string, string> columnList = new Dictionary<string, string>();

        //查询最大值条件
        private List<string> maxCodition = new List<string>();

        //查询最小值条件
        private List<string> minCodition = new List<string>();

        //查询平均值条件
        private List<string> avgCodition = new List<string>();

        //查询数据的业务对象
        private ActualDataManage actualDataManage = new ActualDataManage();

        /// <summary>
        /// 初始化DataGridView
        /// </summary>
        private void IntialDataGridView()
        {
            this.dgv_Main.Columns.Clear();
            columnList.Clear();
            columnList.Add("InsertTime", "日期时间");

            foreach (var item in CommomMethods.plcDevice.StoreVarList)
            {
                columnList.Add(item.VarName, item.Comments);
                maxCodition.Add($"Max( {item.VarName} )");
                minCodition.Add($"Min( {item.VarName} )");
                avgCodition.Add($"Avg( {item.VarName} )");
            }

            foreach (var item in columnList.Keys)
            {
                //创建一个  DataGridTextBoxColumn对象
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();

                //属性赋值
                column.HeaderText = columnList[item];
                column.ReadOnly = true;
                column.Width = item == "InsertTime" ? 170 : 140;
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
                this.dgv_Main.Columns.Add(column);
            }

        }

        private void Cmb_ReportType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cmb_ReportType.SelectedIndex)
            {
                case 0:
                    this.dtp_DateTime.CustomFormat = "yyyy-MM-dd HH:00:00";
                    break;
                case 1:
                    this.dtp_DateTime.CustomFormat = "yyyy-MM-dd 00:00:00";
                    break;
                default:
                    this.dtp_DateTime.CustomFormat = "yyyy-MM-dd 00:00:00";
                    break;
            }
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            //清除DataGridView数据
            this.dgv_Main.Rows.Clear();

            List<string> startList = new List<string>();
            List<string> endList = new List<string>();
            List<string> conditionList = this.rab_Max.Checked ? maxCodition : this.rdb_Min.Checked ? minCodition : avgCodition;

            DateTime dateTime = Convert.ToDateTime(this.dtp_DateTime.Text);

            switch (this.cmb_ReportType.SelectedIndex)
            {
                //小时报表
                case 0:
                    for (int i = 0; i < 60; i++)
                    {
                        startList.Add(dateTime.AddMinutes(i).ToString("yyyy-MM-dd HH:mm:ss"));
                        endList.Add(dateTime.AddMinutes(i + 1).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    break;
                //日报表
                case 1:
                    for (int i = 0; i < 24; i++)
                    {
                        startList.Add(dateTime.AddHours(i).ToString("yyyy-MM-dd HH:mm:ss"));
                        endList.Add(dateTime.AddHours(i + 1).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    break;
                default:
                    break;
            }

            // 获取到时间的区间以及条件
            FrmWaitTip frmWaitTip = new FrmWaitTip();
            frmWaitTip.Show();

            Task.Factory.StartNew(() =>
            {
                Task<DataTable>[] tastList = new Task<DataTable>[startList.Count];

                for (int i = 0; i < startList.Count; i++)
                {
                    tastList[i] = Task.Factory.StartNew((index) =>
                    {
                        System.Threading.Thread.Sleep(100);
                        return actualDataManage.QueryRePortDataByCondition(startList[(int)index], endList[(int)index], conditionList, "table_" + index.ToString());
                    }, i);
                }

                Task<DataTable[]> tast = Task.WhenAll(tastList);

                //将DataTable数组合并成一个DataTable
                DataTable data = GetAllDataTable(tast.Result);

                this.Invoke(new Action(() =>
                {
                    frmWaitTip.Close();

                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        int rowCount = this.dgv_Main.Rows.Add();
                        this.dgv_Main.Rows[rowCount].Cells[0].Value = startList[rowCount];
                        for (int j = 0; j < data.Columns.Count; j++)
                        {
                            object result = data.Rows[rowCount][j];

                            //对数据做一些判断
                            if (result is DBNull)
                            {
                                this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = 0.0;
                            }
                            else
                            {
                                try
                                {
                                    this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = Convert.ToDouble(result).ToString("f2");
                                }
                                catch (Exception)
                                {
                                    this.dgv_Main.Rows[rowCount].Cells[j + 1].Value = 0.0;
                                }
                            }
                        }
                    }
                }));
            });
        }

        /// <summary>
        /// 将多个相同表结构合并成一个表数据表
        /// </summary>
        /// <param name="dataTables"></param>
        /// <returns></returns>
        private DataTable GetAllDataTable(DataTable[] dataTables)
        {
            //复制已有的数据表结构
            DataTable resultTable = dataTables[0].Clone();

            //创建一个行数据数组
            object[] rowdata = new object[resultTable.Columns.Count];
            for (int i = 0; i < dataTables.Length; i++)
            {
                for (int j = 0; j < dataTables[i].Rows.Count; j++)
                {
                    dataTables[i].Rows[j].ItemArray.CopyTo(rowdata, 0);
                    resultTable.Rows.Add(rowdata);
                }
            }
            return resultTable;
        }

        private void dgv_Main_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }

        private void btn_ExPort_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "xls文件(*.xls)|*.xls|所有文件|*.*";
            saveFileDialog.Title = "导出数据报表";
            saveFileDialog.FileName = "数据报表" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xls";
            saveFileDialog.AddExtension = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (ToolsLib.ExcelHelper.DataGridViewToExcel(saveFileDialog.FileName, this.dgv_Main))
                {
                    Process.Start(saveFileDialog.FileName);
                }
                else
                {
                    new FrmMessageBoxWithoutAck("数据报表导出失败", "导出数据报表").ShowDialog();
                }
            }
        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            PrintDGV.Print_DataGridView(this.dgv_Main);
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }
        #endregion
    }
}
